package flc.ast.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Dialog;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.SeekBar;
import android.widget.TextView;

import com.banshengyanyu.bottomtrackviewlib.TrackModel;
import com.banshengyanyu.bottomtrackviewlib.interfaces.ClipVideoListener;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.stark.ve.EditorHolder;
import com.stark.ve.core.IEditorListener;

import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.databinding.ActivityVideoCutBinding;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.TimeUtil;

public class VideoCutActivity extends BaseAc<ActivityVideoCutBinding> implements ClipVideoListener {

    public static String videoPath;
    private long videoLength;
    private long tailorStartTime;
    private long tailorEndTime;
    private Dialog myTipDialog;
    private Handler mHandler;
    private final Runnable mTaskUpdateTime = new Runnable() {
        @Override
        public void run() {
            mDataBinding.tvVideoLeftText.setText(TimeUtil.getMmss(mDataBinding.videoView.getCurrentPosition()));
            mDataBinding.sbVideoPlay.setProgress(Integer.parseInt(TimeUtils.millis2String(mDataBinding.videoView.getCurrentPosition(), "ss")));
            mHandler.postDelayed(this, 500);
        }
    };

    @Override
    protected int onCreate() {
        return R.layout.activity_video_cut;
    }

    @Override
    public void onBackPressed() {
        myTipDialog.show();
    }

    @Override
    protected void initView() {
        mDataBinding.ivVideoCutBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.ivVideoPlay.setOnClickListener(this);
        mDataBinding.tvVideoCutSave.setOnClickListener(this);
        tipDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()){
            case R.id.ivVideoPlay://播放/暂停
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivVideoPlay.setImageResource(R.drawable.icon_bf);
                    mDataBinding.videoView.pause();
                    stopTime();
                } else {
                    mDataBinding.ivVideoPlay.setImageResource(R.drawable.icon_zt);
                    mDataBinding.videoView.start();
                    startTime();
                }
                break;
            case R.id.tvVideoCutSave:
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivVideoPlay.setImageResource(R.drawable.icon_bf);
                    mDataBinding.videoView.pause();
                    stopTime();
                }
                saveVideo();
                break;
            //提示弹框
            case R.id.tvDialogTipCancel://取消
                myTipDialog.dismiss();
                break;
            case R.id.tvDialogTipRight://确定
                myTipDialog.dismiss();
                finish();
                break;
        }
    }

    @Override
    protected void initData() {
        if (TextUtils.isEmpty(videoPath)) return;
        videoLength = MediaUtil.getDuration(videoPath);
        setPlayer();
        //设置剪切功能
        mDataBinding.bottomTrackView.setClipVideoMode(TrackModel.ClipVideoMode.OPERATION);
        mDataBinding.bottomTrackView.setMode(TrackModel.ClipMode.CLIP);
        mDataBinding.bottomTrackView.initInfo(videoPath, videoLength, true,
                0, videoLength, 1.0f);
        mDataBinding.bottomTrackView.setClipVideoListener(this);
    }

    //剪切视频
    private void saveVideo() {
        if (tailorEndTime == 0 && tailorStartTime == 0) {
            ToastUtils.showShort(R.string.cut_tip);
        } else {
            mDataBinding.tvVideoCutSave.setEnabled(false);
            EditorHolder.editor().videoCut(videoPath, tailorStartTime, tailorEndTime, new IEditorListener() {
                @Override
                public void onSuccess(String outFilePath) {
                    dismissDialog();
                    FileP2pUtil.copyPrivateVideoToPublic(mContext, outFilePath);
                    mDataBinding.tvVideoCutSave.setEnabled(true);
                    ToastUtils.showShort(R.string.save_suc);
                    startActivity(HomeActivity.class);
                }

                @Override
                public void onFailure(String errMsg) {
                    dismissDialog();
                    mDataBinding.tvVideoCutSave.setEnabled(true);
                    ToastUtils.showShort(R.string.cut_def);
                }

                @Override
                public void onProgress(int progress) {
                    showDialog(getString(R.string.save_video_ing) + progress + "%");
                }
            });
        }
    }

    //设置播放器
    private void setPlayer() {
        mHandler = new Handler();
        //设置seekbar
        mDataBinding.tvVideoLeftText.setText("00:00");
        mDataBinding.tvVideoRightText.setText(TimeUtil.getMmss(videoLength));
        mDataBinding.sbVideoPlay.setMax(Integer.parseInt(TimeUtils.millis2String(videoLength, "ss")));
        mDataBinding.sbVideoPlay.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mDataBinding.videoView.seekTo(seekBar.getProgress());
            }
        });
        //设置播放器
        mDataBinding.videoView.setVideoPath(videoPath);
        mDataBinding.videoView.seekTo(1);
        mDataBinding.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {  // 播放完成的监听
                mDataBinding.tvVideoLeftText.setText("00:00");
                mDataBinding.tvVideoRightText.setText(TimeUtil.getMmss(videoLength));
                mDataBinding.sbVideoPlay.setProgress(0);
                mDataBinding.ivVideoPlay.setImageResource(R.drawable.icon_bf);
                mp.seekTo(1);
                stopTime();
            }
        });
        //开始播放视频
        mDataBinding.ivVideoPlay.setImageResource(R.drawable.icon_zt);
        mDataBinding.videoView.start();
        startTime();
    }

    private void startTime() {
        mHandler.post(mTaskUpdateTime);
    }

    private void stopTime() {
        mHandler.removeCallbacks(mTaskUpdateTime);
    }

    @Override
    protected void onStop() {
        super.onStop();
        mDataBinding.ivVideoPlay.setImageResource(R.drawable.icon_bf);
        mDataBinding.videoView.pause();
        stopTime();
    }

    //提示弹框
    private void tipDialog() {
        myTipDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_tip, null);
        myTipDialog.setContentView(inflate);
        myTipDialog.setCancelable(true);
        Window dialogWindow = myTipDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.8);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView cancel = inflate.findViewById(R.id.tvDialogTipCancel);
        TextView right = inflate.findViewById(R.id.tvDialogTipRight);
        cancel.setOnClickListener(this);
        right.setOnClickListener(this);
    }


    @Override
    public void clipLeftSliderChange(long duration, long cutStartTime, long cutEndTime, long originTrimIn, long originTrimOut) {
        tailorStartTime = cutStartTime;
        tailorEndTime = cutEndTime;
    }

    @Override
    public void clipRightSliderChange(long duration, long cutStartTime, long cutEndTime, long originTrimIn, long originTrimOut) {
        tailorStartTime = cutStartTime;
        tailorEndTime = cutEndTime;
    }

    @Override
    public void cropFirstLeftSliderChange(long duration, long cutStartTime, long cutEndTime, long originTrimIn, long originTrimOut) {

    }

    @Override
    public void cropFirstRightSliderChange(long duration, long cutStartTime, long cutEndTime, long originTrimIn, long originTrimOut) {

    }

    @Override
    public void cropSecondLeftSliderChange(long duration, long cutStartTime, long cutEndTime, long originTrimIn, long originTrimOut) {

    }

    @Override
    public void cropSecondRightSliderChange(long duration, long cutStartTime, long cutEndTime, long originTrimIn, long originTrimOut) {

    }

    @Override
    public void splitFirstSliderChange(long duration, long cutStartTime, long cutEndTime, long originTrimIn, long originTrimOut) {

    }

    @Override
    public void splitSecondSliderChange(long duration, long cutStartTime, long cutEndTime, long originTrimIn, long originTrimOut) {

    }
}